<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/1/6/006
 * Time: 13:02
 */

namespace app\api\service;


class Upload {

    public static function upload_image() {
        // 获取表单上传文件 例如上传了001.jpg
        try {

            file_put_contents('../runtime/upload_img.txt', " \n \n 111" , FILE_APPEND);

            file_put_contents('../runtime/upload_img.txt', " \n \n " . json_encode($_FILES) , FILE_APPEND);
            $files = request()->file('image');

            $type = input('param.image_type', 'images');

            $paths = [];
            if($files) {
                file_put_contents('../runtime/upload_img.txt', " \n \n 333" , FILE_APPEND);
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $files->validate(['ext'=>'jpg,jpeg,png,gif'])->move('./uploads' . DIRECTORY_SEPARATOR . $type);
                if($info){
                    file_put_contents('../runtime/upload_img.txt', " \n \n 444 - " . $info->getSaveName() , FILE_APPEND);
                    // 成功上传后 获取上传信息
                    $path = './uploads' . DIRECTORY_SEPARATOR . $type . DIRECTORY_SEPARATOR . $info->getSaveName();
                }else{
                    file_put_contents('../runtime/upload_img.txt', " \n \n 555 - " . $files->getError() , FILE_APPEND);
                    // 上传失败获取错误信息
                    return json(['code' => 0, 'msg' => $files->getError()]);
                }

                file_put_contents('../runtime/upload_img.txt', " \n \n path - " . json_encode($paths) , FILE_APPEND);
                $thumb_images = [];
//                foreach ($paths as $path) {
                $image = \think\Image::open($path);
                $ext = substr($path, strrpos($path, '.'));
                $thumb_path =  str_replace($ext, '-thumb' . $ext, $path);
                $big_thumb_path =  str_replace($ext, '-new-thumb' . $ext, $path);

                $image->thumb(750, 750)->save($big_thumb_path);
                $image->thumb(375, 375)->save($thumb_path);

                unlink($path);

                $thumb_images = [
//                    'path' =>\think\facade\Request::domain() . '/' . $path,
                    'thumb_path' => \think\facade\Request::domain() . '/' . $thumb_path,
                    'path' => \think\facade\Request::domain() . '/' . $big_thumb_path,
                ];
//                }
                return $thumb_images;
            } else {
                throw new \Exception('上传文件不存在');
            }
        } catch (\Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }

    }
}